package cn.newshasha.hlx.utils;

import cn.newshasha.hlx.model.PostsJsonRootBean;
import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;

/**提取的关于hlx会用常用的方法集合
 * @author bSu
 * @date 2020/11/28 - 15:53
 */
public class HlxUtils {

    private static Logger logger = Logger.getLogger(HlxUtils.class);

    //private static final String postAdds = "";

    private static String getName(){
        return HlxUtils.class.getName();
    }

    /**
     * 通过帖子地址获取帖子id
     * @param postAdds
     * @return
     */
    public static long getPostId(String postAdds)  {
        try {
            Document doc = Jsoup.connect(postAdds)
                    .timeout(30000)
                    .post();
            String attr = doc.getElementById("postid").attr("value");
            return Long.parseLong(attr);
        }catch (IOException e){
            logger.error(getName()+".getPostId(),io流处理异常",e);
            return 0L;
        }catch (Exception e){
            logger.error(getName()+".getPostId(),Exception异常",e);
            return 0L;
        }
    }

    /**
     * 通过帖子id获取帖子详情
     * @param postId
     */
    public static PostsJsonRootBean getPostDetails(String postId) throws IOException {
        String postJsonUrl="http://floor.huluxia.com/post/detail/ANDROID/2.3?platform=2&gkey=000000&app_version=4.0.0.9.1&versioncode=20141440&market_id=floor_web&post_id="+postId+"&page_no=1&page_size=20&doc=1";
        Connection.Response response = HttpUtils.get(postJsonUrl);
        String body = response.body();
        JSONObject json=new JSONObject();
        PostsJsonRootBean jsonRootBean = json.parseObject(response.body(), PostsJsonRootBean.class);
        return jsonRootBean;
    }

    /**
     * 通过帖子id和页码获取帖子回复（翻页后post值为null）
     * @param postId
     */
    public static PostsJsonRootBean getPostDetailsByPage(String postId,String pageNo) throws IOException {
        String postJsonUrl="http://floor.huluxia.com/post/detail/ANDROID/2.3?platform=2&gkey=000000&app_version=4.0.0.9.1&versioncode=20141440&market_id=floor_web&post_id="+postId+"&page_no="+pageNo+"&page_size=20&doc=1";
        Connection.Response response = HttpUtils.get(postJsonUrl);
        String body = response.body();
        JSONObject json=new JSONObject();
        PostsJsonRootBean jsonRootBean = json.parseObject(response.body(), PostsJsonRootBean.class);
        return jsonRootBean;
    }

}
